import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { useUserStore } from "@/store/model/user";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/home",
    name: "home",
    component: () => import("../views/my-home.vue"),
  },
  {
    path: "/map/:id",
    name: "map",
    component: () => import("../views/my-map.vue"),
  },
  {
    path: "/toLogin",
    name: "toLogin",
    component: () => import("../pages/to-login.vue"),
  },
  {
    path: "/toHome",
    name: "toHome",
    component: () => import("../pages/to-home.vue"),
  },
  { path: "/", redirect: "/home" },
  // { path: "/", redirect: "/toLogin" },
];

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from) => {
  const userStore = useUserStore();
  const user = userStore.getUser();
  const token = userStore.getToken();
  const userItem = window.sessionStorage.getItem("user");
  const tokensItem = window.localStorage.getItem("token");
  if (!token && tokensItem) {
    userStore.setToken(tokensItem);
  }
  if (!user && userItem) {
    userStore.setUser(userItem);
  }
  if (!tokensItem || !userItem) {
    // todo 返回微信小程序
  }
});

export default router;
